package com.bjbn.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjbn.bean.BaParam;
import com.bjbn.service.BaService;
import com.bjbn.util.SSLUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ba")
@Slf4j
public class BaController {
    @Autowired
    private BaService baService;

    @Value("${ba-w-config.ba-base-url}")
    private String baBaseUrl4W;

    @Value("${ba-e-config.ba-base-url}")
    private String baBaseUrl4E;

    @Value("${ba-t3-config.ba-base-url}")
    private String baBaseUrl4T3;

    @Value("${default-position}")
    private String defaultPosition;

    @RequestMapping("/login")
    public JSONObject login(@RequestBody BaParam param) {
        JSONObject jsonObject = new JSONObject();
        String position = param.getPosition();
        // 如果区域为空或者区域不等于 东四：EAST；西四：WEST T3: T3 设置为默认区域
        if (StringUtils.isEmpty(position)) {
            position = defaultPosition;
            param.setPosition(position);
        } else if (!"EAST".equals(position) && !"WEST".equals(position) && !"T3".equals(position)) {
            position = defaultPosition;
            param.setPosition(position);
        }

        String token = baService.getBaToken(param.getPosition());

        jsonObject.put("data", token);
        jsonObject.put("code", 200);
        jsonObject.put("msg", "this link visit success");
        jsonObject.put("success", true);
        return jsonObject;
    }

    @RequestMapping("/relogin")
    public JSONObject relogin(@RequestBody BaParam param) {
        JSONObject jsonObject = new JSONObject();
        String position = param.getPosition();
        // 如果区域为空或者区域不等于 东四：EAST；西四：WEST T3: T3 设置为默认区域
        if (StringUtils.isEmpty(position)) {
            position = defaultPosition;
            param.setPosition(position);
        } else if (!"EAST".equals(position) && !"WEST".equals(position) && !"T3".equals(position)) {
            position = defaultPosition;
            param.setPosition(position);
        }

        String token = baService.refreshBaToken(param.getPosition());

        jsonObject.put("data", token);
        jsonObject.put("code", 200);
        jsonObject.put("msg", "this link visit success");
        jsonObject.put("success", true);
        return jsonObject;
    }

    @RequestMapping("/ctrl")
    public JSONObject ctrl(@RequestBody BaParam param) {
        String url = "";
        String position = param.getPosition();

        // 如果区域为空或者区域不等于 东四：EAST；西四：WEST T3: T3 设置为默认区域
        if (StringUtils.isEmpty(position)) {
            position = defaultPosition;
            param.setPosition(position);
        } else if (!"EAST".equals(position) && !"WEST".equals(position) && !"T3".equals(position)) {
            position = defaultPosition;
            param.setPosition(position);
        }

        if ("WEST".equals(param.getPosition())) {
            url = baBaseUrl4W;
        } else if ("EST".equals(param.getPosition())) {
            url = baBaseUrl4E;
        } else if ("T3".equals(param.getPosition())) {
            url = baBaseUrl4T3;
        }

        String ctrlUrl = url + "/API/api/commands/" + param.getCtrlId() + ".Present_Value/Write";
        String dataType = "";
        String value = param.getValue();
        String authorization = "Bearer " + baService.getBaToken(param.getPosition());
        String stateUrl = url + "/API/api/values/" + param.getCtrlId();

        // 获取状态
        HttpRequest request0 = HttpUtil
                .createGet(stateUrl)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", "Bearer " + baService.getBaToken(param.getPosition()))
                .setSSLSocketFactory(SSLUtils.getSSLSocketFactory());
        HttpResponse response0 = request0.execute();
        System.out.println("状态接口返回: " + response0.getStatus());
        System.out.println("状态接口返回: " + response0.body());
        log.info("状态接口返回: " + response0.getStatus());
        JSONArray array = JSONArray.parseArray(response0.body());
        JSONObject state = array.getJSONObject(0);
        dataType = state.getString("DataType");

        if ("ExtendedEnum".equals(dataType)) {
            // 如果是开关量，value不是0和1则是无效指令
            if (!"0".equals(value) && !"1".equals(value)) {
                return null;
            }
        }
        // 发送执行指令
        HttpRequest request1 = HttpUtil
                .createPost(ctrlUrl)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", authorization)
                .header("Content-Type", "application/json")
                .setSSLSocketFactory(SSLUtils.getSSLSocketFactory())
                .body("[{\"Name\":\"Value\",\"DataType\":\"" + dataType + "\",\"Value\":\"" + value + "\"}]");

        System.out.println("控制指令url: " + ctrlUrl);
        String b = "[{\"Name\":\"Value\",\"DataType\":\"" + dataType + "\",\"Value\":\"" + value + "\"}]";
        System.out.println("控制指令body: " + b);

        HttpResponse response1 = request1.execute();
        System.out.println("Response1 Status: " + response1.getStatus());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", response1.body());
        jsonObject.put("code", 200);
        jsonObject.put("msg", "this link visit success");
        jsonObject.put("success", true);
        return jsonObject;
    }

    @RequestMapping("/ctrlpure")
    public JSONObject ctrlpure(@RequestBody BaParam param) {
        String url = "";
        String position = param.getPosition();

        // 如果区域为空或者区域不等于 东四：EAST；西四：WEST T3: T3 设置为默认区域
        if (StringUtils.isEmpty(position)) {
            position = defaultPosition;
            param.setPosition(position);
        } else if (!"EAST".equals(position) && !"WEST".equals(position) && !"T3".equals(position)) {
            position = defaultPosition;
            param.setPosition(position);
        }

        if ("WEST".equals(param.getPosition())) {
            url = baBaseUrl4W;
        } else if ("EAST".equals(param.getPosition())) {
            url = baBaseUrl4E;
        } else if ("T3".equals(param.getPosition())) {
            url = baBaseUrl4T3;
        }

        String commandUrl = url + "/API/api/commands/" + param.getCtrlId() + ".Present_Value";
        String ctrlUrl = url + "/API/api/commands/" + param.getCtrlId() + ".Present_Value/Write";
        String dataType = "";
        String value = param.getValue();
        String authorization = "Bearer " + baService.getBaToken(param.getPosition());
        // 获取指令列表
        HttpRequest request0 = HttpUtil
                .createGet(commandUrl)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", authorization)
                .setSSLSocketFactory(SSLUtils.getSSLSocketFactory());
        HttpResponse response0 = request0.execute();
        if (response0.getStatus() != 200) {
            return null;
        }
        JSONArray commandsResArray = JSONArray.parseArray(response0.body());
        JSONObject commands = commandsResArray.getJSONObject(0);
        JSONArray commandsArray = commands.getJSONArray("Commands");
        for (int i = 0; i < commandsArray.size(); i++) {
            JSONObject command = commandsArray.getJSONObject(i);
            if (command.getString("Id").equals("Write")) {
                JSONObject parameter = command.getJSONArray("Parameters").getJSONObject(0);
                dataType = parameter.getString("DataType");
            }
        }
        if ("ExtendedEnum".equals(dataType)) {
            // 如果是开关量，value不是0和1则是无效指令
            if (!"0".equals(value) && !"1".equals(value)) {
                return null;
            }
        }
        // 发送执行指令
        HttpRequest request1 = HttpUtil
                .createPost(ctrlUrl)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", authorization)
                .header("Content-Type", "application/json")
                .setSSLSocketFactory(SSLUtils.getSSLSocketFactory())
                .body("[{\"Name\":\"Value\",\"DataType\":\"" + dataType + "\",\"Value\":\"" + value + "\"}]");

        HttpResponse response1 = request1.execute();
        System.out.println("指令接口返回: " + response1.getStatus());
        System.out.println("指令接口返回: " + response1.body());
        log.info("指令接口返回: " + response1.getStatus());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", response1.body());
        jsonObject.put("code", 200);
        jsonObject.put("msg", "this link visit success");
        jsonObject.put("success", true);
        return jsonObject;
    }

    @RequestMapping("/state")
    public JSONObject state(@RequestBody BaParam param) {
        String url = "";
        String position = param.getPosition();

        // 如果区域为空或者区域不等于 东四：EAST；西四：WEST T3: T3 设置为默认区域
        if (StringUtils.isEmpty(position)) {
            position = defaultPosition;
            param.setPosition(position);
        } else if (!"EAST".equals(position) && !"WEST".equals(position) && !"T3".equals(position)) {
            position = defaultPosition;
            param.setPosition(position);
        }

        if ("WEST".equals(param.getPosition())) {
            url = baBaseUrl4W;
        } else if ("EAST".equals(param.getPosition())) {
            url = baBaseUrl4E;
        } else if ("T3".equals(param.getPosition())) {
            url = baBaseUrl4T3;
        }

        String stateUrl = url + "/API/api/values/" + param.getStateId();

        // 获取状态
        HttpRequest request2 = HttpUtil
                .createGet(stateUrl)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", "Bearer " + baService.getBaToken(param.getPosition()))
                .setSSLSocketFactory(SSLUtils.getSSLSocketFactory());
        HttpResponse response2 = request2.execute();
        System.out.println("状态接口返回: " + response2.getStatus());
        System.out.println("状态接口返回: " + response2.body());
        log.info("状态接口返回: " + response2.getStatus());
        JSONArray array = JSONArray.parseArray(response2.body());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", array.getJSONObject(0));
        jsonObject.put("code", 200);
        jsonObject.put("msg", "this link visit success");
        jsonObject.put("success", true);
        return jsonObject;
    }

}
